import numpy as np
from decimal import Decimal
from collections.abc import Iterable
from fractions import Fraction

#原始数据归一处理
def dataNormaliza(*data):

    #将java BigDecimal[][]转np.array
    np_2d_array = np.array(
        [[Decimal(str(s))for s in row]for row in data],
        dtype=object
    )
    #print("np_2d_array: ",np_2d_array)

    RO = np_2d_array[:,7]
    #print("-------RO--------",RO)
    KK = np_2d_array[:,8]
    #print("KK: ",KK)
    averageArr = []
    rowAll = []
    #根据阈值筛选出接近均值的数据
    average = remove_outliers(RO)
    #print("-------average--------",average)
    print("电阻率处理成功")
    averageArr.append(np.array(average))
    #挑选电阻率接近的行数据
    for index,das in enumerate(averageArr):
        #print("index: ",index)
        #print("das: ",das)
        oneList = []
        oneListunique = []
        for das1 in das:
            #print("das1: ",das1)
            selctOne,indx = select_rows_list(np_2d_array,das1)
            # print("打印滤波后的行： ",selctOne)
            # print("打印滤波后的行indx： ",indx)
            flattened_list = list(flatten(selctOne))
            if len(flattened_list) >0:
                oneList.append(flattened_list)
            #rowAll.append(flattened_list)


        #arrList = np.array(oneList)
        arrList = np.array(
            [[Decimal(str(s)) for s in row] for row in oneList],
            dtype=object
        )
        # 将字符串数组转换为浮点型数组
        #float_array = arrList.astype(float)

        # print(type(arrList))
        aa = str(np.unique(arrList[:,0])[0])
        bb = str(np.unique(arrList[:,1])[0])
        mm = str(np.unique(arrList[:,2])[0])
        nn = str(np.unique(arrList[:,3])[0])
        tx_v = arrList[:,4]
        btxV1 = [num for num in tx_v]
        #print("brxV1: ",brxV1)
        #tx_v_avg = np.mean(brxV1)
        tx_v_avg = format(np.sqrt(np.mean(np.square(btxV1))), '.5f')
        #print("tx_v_avg: ",tx_v_avg)
        tx_i = arrList[:,5]
        btxI1 = [num for num in tx_i]
        #tx_i_avg = np.mean(btxI1)
        tx_i_avg = format(np.sqrt(np.mean(np.square(btxI1))), '.5f')
        rx_v = arrList[:,6]
        brxV1 = [num for num in rx_v]
        #rx_v_avg = np.mean(brxV1)
        rx_v_avg = format(np.sqrt(np.mean(np.square(brxV1))), '.5f')
        oneListunique.append(aa)
        oneListunique.append(bb)
        oneListunique.append(mm)
        oneListunique.append(nn)
        oneListunique.append(1)#Stacking 循环次数
        oneListunique.append(KK[0])#K装置系数
        #oneListunique.append(tx_v_avg)
        oneListunique.append(tx_i_avg)#发射电流
        oneListunique.append(rx_v_avg)#接收电压
        oneListunique.append(round(KK[0]*(Decimal(rx_v_avg)/Decimal(tx_i_avg)),5))#电阻率R
        oneListunique.append(0)#接地电阻率R0
        oneListunique.append(0)#自然电位SP
        oneListunique.append(0)#可能是测量误差R0_RD
        oneListunique.append(round(Decimal(rx_v_avg)/Decimal(tx_v_avg)*100,5))#IP极化率
        oneListunique.append(";")
        #print("oneListunique: ",oneListunique)
        result = str(oneListunique)
        #print("result: ",result)
    return result

def java_array_to_numpy(java_array, dtype=np.float64):
    """
    将Java数组转换为NumPy数组。

    参数:
    java_array (list或嵌套list): 表示Java数组的Python列表
    dtype (numpy数据类型, 可选): 结果数组的数据类型，默认为float64

    返回:
    numpy.ndarray: 转换后的NumPy数组
    """
    # 检查是否为多维数组（嵌套列表）
    return np.array([java_array_to_numpy(sub_array, dtype) for sub_array in java_array], dtype=dtype)
def select_rows_list(csvAllLis,val):
    selected_rows = []
    if len(csvAllLis) >0:
        for index,row in enumerate(csvAllLis):
            #print("row: ",row)
            if val == row[7]:
                if(len(selected_rows) == 0):
                    selected_rows.append(row)
            #csvAllLis.pop(index)
    return selected_rows,index

def remove_outliers(data, threshold=3):
    """
    使用Z-score方法去除异常点
    """
    data_new = data
    z_scores = np.array(np.abs((data_new - np.mean(data_new)) / np.std(data_new)))
    # 通常Z-score大于3被认为是异常点
    print("z_scores type: ",len(data_new))
    print("z_scores type: ",len(z_scores))
    return np.array(data_new)[z_scores < threshold]
def flatten(lst):
    for item in lst:
        if isinstance(item, Iterable) and not isinstance(item, (str, bytes)):
            yield from flatten(item)
        else:
            yield item
def getKVal(A,B,M,N):
    # # 创建分数对象
    # am = Fraction(1, AM)   # 表示 1/2
    # an = Fraction(1, AN)   # 表示 3/4
    # bm = Fraction(1, BM)   # 表示 1/2
    # bn = Fraction(1, BN)   # 表示 3/4
    # # 基本运算
    # sub_amn = am - an     # 加法: 1/2 + 3/4 = 5/4
    # sub_amn_new = sub_amn - bm     # 加法: 1/2 + 3/4 = 5/4
    # #print("sub_amn: ",sub_amn)
    # sum_result = abs(sub_amn_new + bn)       # 减法: 1/2 - 3/4 = -1/4
    # #print("sum_result: ",sum_result)
    # kv = round(2*np.pi/sum_result, 5)
    # 计算各电极间距离
    AM = abs(M - A)
    BM = abs(M - B)
    AN = abs(N - A)
    BN = abs(N - B)

    # 计算装置系数
    denominator = (1/AM - 1/AN - 1/BM + 1/BN)
    K = abs(round((2 * np.pi / denominator),5))

    #print("kv: ",K)
    return K